<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\UserStatistic;
use App\Models\UserTier;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Auth;
use Illuminate\Auth\Events\Registered;

class AuthController extends Controller
{
    /**
     * 用户注册
     */
    public function register(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'username' => 'required|string|min:3|max:50|unique:users',
            'email' => 'required|email|unique:users',
            'password' => 'required|string|min:8|confirmed'
        ]);

        if ($validator->fails()) {
            return $this->error('输入数据验证失败', 422, $validator->errors());
        }

        try {
            $user = User::create([
                'username' => $request->username,
                'email' => $request->email,
                'password' => Hash::make($request->password),
            ]);

            // 创建用户统计记录
            UserStatistic::create([
                'user_id' => $user->id,
            ]);

            // 创建初始段位
            UserTier::create([
                'user_id' => $user->id,
                'tier_name' => 'Social Seed',
                'tier_level' => 1,
                'experience_points' => 0,
                'is_current' => true,
            ]);

            // 触发注册事件（用于邮箱验证）
            event(new Registered($user));

            // 生成访问令牌
            $token = $user->createToken('SocialDojo')->accessToken;

            return $this->success([
                'user' => [
                    'id' => $user->id,
                    'username' => $user->username,
                    'email' => $user->email,
                    'email_verified_at' => $user->email_verified_at,
                    'avatar_url' => $user->avatar_url,
                ],
                'access_token' => $token,
                'token_type' => 'Bearer',
            ], '注册成功');

        } catch (\Exception $e) {
            return $this->error('注册失败，请稍后重试', 500);
        }
    }

    /**
     * 用户登录
     */
    public function login(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'email' => 'required|email',
            'password' => 'required|string'
        ]);

        if ($validator->fails()) {
            return $this->error('输入数据验证失败', 422, $validator->errors());
        }

        if (!Auth::attempt($request->only('email', 'password'))) {
            return $this->error('邮箱或密码错误', 401);
        }

        $user = Auth::user();
        $token = $user->createToken('SocialDojo')->accessToken;

        return $this->success([
            'user' => [
                'id' => $user->id,
                'username' => $user->username,
                'email' => $user->email,
                'email_verified_at' => $user->email_verified_at,
                'avatar_url' => $user->avatar_url,
            ],
            'access_token' => $token,
            'token_type' => 'Bearer',
        ], '登录成功');
    }

    /**
     * 获取当前用户信息
     */
    public function me(Request $request)
    {
        $user = $request->user();
        
        return $this->success([
            'id' => $user->id,
            'username' => $user->username,
            'email' => $user->email,
            'email_verified_at' => $user->email_verified_at,
            'avatar_url' => $user->avatar_url,
            'created_at' => $user->created_at,
        ]);
    }

    /**
     * 用户登出
     */
    public function logout(Request $request)
    {
        $request->user()->token()->revoke();
        
        return $this->success(null, '登出成功');
    }

    /**
     * 邮箱验证
     */
    public function verifyEmail(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'verification_code' => 'required|string'
        ]);

        if ($validator->fails()) {
            return $this->error('验证码不能为空', 422, $validator->errors());
        }

        // 这里应该实现邮箱验证逻辑
        // 暂时简化处理
        $user = $request->user();
        
        if ($user->hasVerifiedEmail()) {
            return $this->error('邮箱已经验证过了', 400);
        }

        $user->markEmailAsVerified();

        return $this->success(null, '邮箱验证成功');
    }

    /**
     * 发送密码重置邮件
     */
    public function forgotPassword(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'email' => 'required|email|exists:users'
        ]);

        if ($validator->fails()) {
            return $this->error('邮箱不存在', 422, $validator->errors());
        }

        // 这里应该实现发送密码重置邮件的逻辑
        // 暂时返回成功响应
        return $this->success(null, '密码重置邮件已发送');
    }

    /**
     * 重置密码
     */
    public function resetPassword(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'token' => 'required|string',
            'email' => 'required|email|exists:users',
            'password' => 'required|string|min:8|confirmed'
        ]);

        if ($validator->fails()) {
            return $this->error('输入数据验证失败', 422, $validator->errors());
        }

        // 这里应该实现密码重置逻辑
        // 暂时简化处理
        $user = User::where('email', $request->email)->first();
        $user->password = Hash::make($request->password);
        $user->save();

        return $this->success(null, '密码重置成功');
    }
}